<?php
$res = include_once("../PHPExcel/PHPExcel.php");
$data=[
    [
        "bo_id"=>16279,
        "goods_id"=>495869,
        "goods_name"=>"秒杀 CONVERSE/匡威 超特价经典款高帮帆布鞋惊喜价（绝版老标拍下不退）"
    ],
    [
        "bo_id"=>1612379,
        "goods_id"=>495812369,
        "goods_name"=>"3123布鞋惊喜价（绝版老标拍下不退）"
    ]
];

$title = array(
    'bo_id'=>'晒单ID',
    "goods_id"=>'商品ID',
    "goods_name"=>'商品名'
);
$filename = '测试晒单列表_' . date('Ymd_His').'.xlsx';
exportexcel($filename, $title,$data);

/**
 * 使用php_excel导出excel
 * @param $filename
 * @param array $titles
 * @param array $dataArray
 * @param string $bigTitle
 * @throws PHPExcel_Exception
 * @throws PHPExcel_Reader_Exception
 * @throws PHPExcel_Writer_Exception
 */
function exportExcel($filename,array $titles, array $dataArray, $bigTitle='')
{
    // 后缀
    $suffix = substr($filename, strrpos($filename, '.'));
    empty($titles) && die('标题数组不能为空！');
    empty($dataArray) && die('数据数组不能为空！');
    !in_array($suffix, ['.xls', '.xlsx']) && die('文件名格式错误！');

    //=====注意命令空间
    $oExcel = new PHPExcel();
    $oExcel->setActiveSheetIndex(0);
    $sheet = $oExcel->getActiveSheet();

    // 行索引
    $rowIndex = $bigTitle!=''? 2:1;

    // 设置大标题
    if ($bigTitle != '') {
        $sheet->mergeCells('A1:'. chr(64+count($titles)) .'1');
        $sheet->getStyle('A1')->applyFromArray([
            'font' => ['bold'=>true],
            //=====注意命令空间
            'alignment' => ['horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER]
        ]);
        $sheet->setCellValue('A1', $bigTitle);
    }

    // 设置标题 A1 B1 C1 ....
    $colIndex = 0;
    $fieldsMap = [];
    foreach ($titles as $key => $title) {
        $fieldsMap[] = $key;
        //$sheet->setCellValue(chr(65+$colIndex) . $rowIndex, $title);
        $sheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($colIndex) . $rowIndex,$title);
        $colIndex++;
    }
    // 设置内容 A1 B1 C1 ....   A2 B2 C2 ....
    $rowIndex++;
    foreach ($dataArray as $key => $value)
    {
        foreach ($fieldsMap as $colIndex => $field) {
            //$sheet->setCellValue(chr(65+$colIndex).$rowIndex, $value[$field]);
            $sheet->setCellValue(\PHPExcel_Cell::stringFromColumnIndex($colIndex) . $rowIndex,$value[$field]);
        }
        $rowIndex++;
    }

    if ($suffix == '.xlsx') {
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    } else {
        header('Content-Type: application/vnd.ms-excel');
    }
    header('Content-Disposition: attachment;filename="'. $filename .'"');

    //=====注意命令空间
    $oWriter = PHPExcel_IOFactory::createWriter($oExcel, 'Excel2007');
    $oWriter->save('php://output');
    $oExcel->disconnectWorksheets();
    exit;
}